package com.bit.springboot_1;


import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

@RestController
@RequestMapping("/cookie")
public class CookieSession {

    @RequestMapping("/getCookie")
    public String getCookie(HttpServletRequest httpServletRequest){
        Cookie[] cookies = httpServletRequest.getCookies();
        if(cookies!=null){
        for(Cookie c:cookies){
            System.out.println(c.getName()+":"+c.getValue());
        }
        }
        return "成功获取cookie";
    }

    @RequestMapping("/setSession")
    public String setSession(String name,HttpServletRequest httpServletRequest){
        HttpSession session=httpServletRequest.getSession();//没有获取到就自动设置
        session.setAttribute("name",name);
        session.setAttribute("age",10);
        return "设置session成功";
    }

    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest httpServletRequest){
        HttpSession session=httpServletRequest.getSession();
        String name=(String)session.getAttribute("name");
        Integer age=(Integer) session.getAttribute("age");

        return "从session中获取信息成功 "+"name="+name+" age="+age;
    }

    @RequestMapping("/getSession2")
    public String getSession2(HttpSession session){
        String name=(String)session.getAttribute("name");
        Integer age=(Integer) session.getAttribute("age");

        return "从session中获取信息成功 "+"name="+name+" age="+age;
    }

    @RequestMapping("/getSession3")
    public String getSession(@SessionAttribute("name")String name){
        return "从session中获取信息成功 "+"name="+name;
    }


}
